package com.hqhy.like.stock.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.hqhy.like.common.pojo.vo.PageData;
import com.hqhy.like.common.web.JsonResult;
import com.hqhy.like.stock.pojo.param.StockInAddParam;
import com.hqhy.like.stock.pojo.param.StockInDeleteParam;
import com.hqhy.like.stock.pojo.param.StockSearchParam;
import com.hqhy.like.stock.pojo.param.StockInUpdateParam;
import com.hqhy.like.stock.pojo.vo.StockInListItemVO;
import com.hqhy.like.stock.service.IStockInService;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 入库管理 的控制层
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/stock/in")
public class StockInController {

    @Autowired
    private IStockInService stockInService;

    /**
     * 新增入库订单
     */
    @PostMapping("/insert")
    public JsonResult insert(@Valid StockInAddParam stockInAddParam) {
        log.debug("开始处理【新增库存】的请求，参数：{}", stockInAddParam);
        stockInService.insert(stockInAddParam);
        return JsonResult.ok();
    }

    /**
     * 根据id删除进货订单
     */
    @PostMapping("/{id:[0-9]+}/delete")
    public JsonResult delete(@PathVariable @Range(min = 1, message = "请提交有效的类别ID值！") Long id) {
        log.debug("开始处理【根据ID删除入库订单】的请求，参数：{}", id);
        stockInService.deleteById(id);
        return JsonResult.ok();
    }

    /**
     * 根据id批量删除入库订单
     */
    @PostMapping("/batch/delete")
    public JsonResult deleteByList(@RequestBody List<StockInDeleteParam> list) {
        log.debug("开始处理【根据id批量删除入库订单】的请求，参数{}", list);
        for (StockInDeleteParam item : list) {
            stockInService.deleteById(item.getId());
        }
        return JsonResult.ok();
    }

    /**
     * 修改入库订单
     */
    @PostMapping("/update")
    public JsonResult delete(@Valid StockInUpdateParam stockInUpdateParam) {
        log.debug("开始处理【更新库存】的请求，参数：{}", stockInUpdateParam);
        stockInService.updateById(stockInUpdateParam);
        return JsonResult.ok();
    }

    /**
     * 查询入库列表
     */
    @GetMapping("/list")
    public JsonResult list(@Range(min = 1, message = "请提交有效的页码值！") Integer page, Integer size) {
        log.debug("开始处理【查询入库列表】的请求，页码：{},每页记录数: {}", page, size);
        Integer pageNum = page == null ? 1 : page;
        PageData<StockInListItemVO> pageData = stockInService.list(pageNum, size);
        return JsonResult.ok(pageData);
    }

    /**
     * 根据ID查询入库单
     */
    @GetMapping("/{id}")
    public JsonResult getStandardById(@PathVariable Long id){
        log.debug("开始处理【根据ID查询入库单】的请求，参数：{}", id);
        StockInListItemVO tag = stockInService.getStockInById(id);
        return JsonResult.ok(tag);
    }

    /**
     * 搜索入库列表
     */
    @PostMapping("/search")
    public JsonResult listForSearch(StockSearchParam stockInSearchParam) {
        log.debug("开始处理【搜索入库列表】的请求，参数{}", stockInSearchParam);
        PageData<StockInListItemVO> pageData = stockInService.listForSearch(stockInSearchParam);
        return JsonResult.ok(pageData);
    }

    /**
     * 导出功能 失败
     */
    @PostMapping("/export")
    public void ExportFile(@RequestBody List<StockInDeleteParam> list, HttpServletResponse response) throws IOException {
        log.debug("开始处理【导出excel】的请求，参数{}", list);
        ArrayList<Long> longs = new ArrayList<>();
        for (StockInDeleteParam item : list) {
            longs.add(item.getId());
        }

        List<StockInListItemVO> rows = CollUtil.newArrayList(stockInService.listForExport(longs));

        log.debug("现在要打印的表格list为: {}" ,rows);
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(rows, true);

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //stock.xlsx是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=stock.xlsx");
        //out为OutputStream，需要写出到的目标流
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        out.flush();;
        response.flushBuffer();
        out.close();
    }

    /**
     * 导入功能
     */
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file)throws IOException{
        List<StockInListItemVO> infoList = ExcelUtil.getReader(file.getInputStream()).readAll(StockInListItemVO.class);
        if (!CollectionUtil.isEmpty(infoList)){
            for (StockInListItemVO item: infoList) {
                try {
                    StockInAddParam stockInAddParam = new StockInAddParam();
                    log.debug("开始处理【插入数据】的请求，参数{}", item);
                    BeanUtils.copyProperties(item,stockInAddParam);
                    log.debug("开始处理【插入数据】的请求，参数{}", stockInAddParam);
                    stockInService.insert(stockInAddParam);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return JsonResult.ok();
    }
}
